<?php

namespace App\Exports;

use App\Models\Department;
use Carbon\Carbon;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use App\Models\User;
use App\Models\CrmConfig;

class ClientExport extends ExcelExporter implements WithMapping, WithHeadings, ShouldAutoSize
{

    //这里是导出来的文件的名字和格式
    protected $fileName = '意向客户列表.xlsx';
    //这里是excel的标题
    public function headings(): array
    {
        return [
            '创建日期',
            '姓名',
            '电话',
            '所属销售人员',
            '上级主管',
            '所属三级部门',
            '所属二级部门',
            '所属一级部门',
            '客户类型',
            '销售跟进状态',
            '最新跟进记录',
            '最新跟进时间',
            '未跟进天数'
        ];
    }

    public function map($client): array
    {	//这里是字段的值 如果是主表的数据 直接对象的形式就可以写出来
        //如果是关联的表的数据 可以通过data_get()去渲染
        //其他部分是枚举类字段值的语义化
        $client_status = CrmConfig::getKeyValue('client_status');
        $follow_status = CrmConfig::getKeyValue('follow_status');
        $l3 = Department::getLevel(3);
        $l2 = Department::getLevel(2);
        $l1 = Department::getLevel(1);
        $users = User::Users();
        $list = [
            $client->employee->dep_l3,
            $client->employee->dep_l2,
            $client->employee->dep_l1,
            $client->status,
            $client->employee_status,
            $client->employee_id,
        ];
        $client_status[0] = $follow_status[0] = $l1[0] = $l2[0] = $l3[0] = $users[0] = $records = $last_updated_at = $nt = '';
        foreach ($list as $key => $item){
            if(empty($item)){
                $list[$key] = 0;
            }
        }

        if(isset( $client->oneLastRecords->updated_at)){
            $last_updated_at = Carbon::parse($client->oneLastRecords->updated_at)->toDateTimeString();
        }
        if(isset($client->oneLastRecords->records)){
            $records = $client->oneLastRecords->records;
            $nt = (int) ceil((time() - strtotime($last_updated_at)) / 60 / 60 / 24);
        }

        $data = [
            $client->true_client_at,
            $client->name,
            $client->mobile,
            $users[$list[5]],
            Department::getLeader($list[5]),
            $l3[$list[0]],
            $l2[$list[1]],
            $l1[$list[2]],
            $client_status[$list[3]],
            $follow_status[$list[4]],
            $records,
            $last_updated_at,
            $nt
        ];
        return $data;
    }



}
